import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * @author suoyue_zhan
 * @date 2021/03/22 09:57
 * @descript Double类型保留小数点4种方法，都是四舍五入
 */
public class DoubleDecimals {

    public static void main(String[] args) {
        double d = 111231.5585;
        bigDecimalDouble(d);
        decimalFormatDouble(d);
        stringFormatDouble(d);
        numberFormatDouble(d);
    }

    /**
     * NumberFormat 返回美元格式
     * @param d
     */
    private static void numberFormatDouble(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        System.out.println(nf.format(d));
    }

    /**
     * String.format打印最简便
     * @param d
     */
    private static void stringFormatDouble(double d) {
        System.out.println(String.format("%.2f", d));
    }

    /**
     * DecimalFormat转换最简便
     * @param d
     */
    private static void decimalFormatDouble(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        System.out.println(df.format(d));
    }

    /**
     * BigDecimal
     * @param d
     */
    private static void bigDecimalDouble(double d) {
        BigDecimal bg = new BigDecimal(d);
        double bf = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println(bf);
    }

}
